<template>
  <div class="body">
    <div class="editAlert" v-if="alertState">
      <div class="Pop_title">
        {{ alertTitle }}
      </div>
      <el-form label-width="130px" :model="editForm" ref="formRef" class="editForm" :rules="editFormRoules">
        <el-form-item label="分组标题" label-position="left" prop="title">
          <el-input v-model.trim="editForm.title" placeholder="请输入分组标题" class="search_input" />
        </el-form-item>
        <el-form-item label="选择门店类型" label-position="left" prop="group_id">
          <el-select v-model="editForm.group_id" placeholder="请选择门店类型" style="width: 240px">
            <el-option v-for="item in group" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="分组图标" label-position="left" prop="img">
          <div class="avatar-uploader">
            <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" :on-change="handleFileChange"
              :on-remove="handleRemove" :on-preview="handleimgsPreview" :file-list="fileimg"
              :class="{ 'hide-upload': fileimg.length > 0 }">
              <template v-if="fileimg.length === 0">
                <el-icon>
                  <Plus />
                </el-icon>
              </template>
              <template v-else>
                <img class="avatar" :src="fileimg[0].url" alt="头像" />
                <span class="avatar-actions">
                  <span class="avatar-delete" @click.stop="handleRemove(fileimg[0])">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </span>
                </span>
              </template>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
      <div class="footer_btn">
        <el-button type="primary" @click="affirm(formRef)">确认</el-button>
        <el-button class="rigthBtn" @click="cancel">取消</el-button>
      </div>
      <el-dialog v-model="imgsState">
        <img w-full :src="dialogImageUrl" alt="Preview Image" class="preview-img" />
      </el-dialog>
    </div>
    <div class="content" v-if="!alertState">
      <div class="search_box">
        <el-form label-width="auto" :model="search" class="search_form ">
          <el-form-item label="分类标题" label-position="top">
            <el-input v-model="search.title" placeholder="请输入标题" class="search_input input_height" @input="searchData" />
          </el-form-item>
          <el-form-item label="创建时间" label-position="top">
            <el-date-picker type="daterange" v-model="search.time" size="default" start-placeholder="开始时间"
              end-placeholder="结束时间" format="YYYY/MM/DD" value-format="YYYY-MM-DD" unlink-panels
              @change="searchData"></el-date-picker>
          </el-form-item>
        </el-form>
      </div>
      <div class="line"></div>
      <div class="operateBtn">
        <el-button type="primary" class="button_height" @click="addAlter">添加</el-button>
        <el-button type="danger" class="button_height" @click="delePop(selectedIds)">批量删除</el-button>
      </div>
      <el-table :data="pageCount" class="label" @selection-change="checkall">
        <el-table-column type="selection" />
        <el-table-column prop="id" label="id" align="center" />
        <el-table-column prop="title" label="名称" align="center" />
        <el-table-column prop="createtime" label="创建时间" align="center" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div class="operate_box">
              <p class="edit" @click="editAlter(scope.row)">编辑</p>
              <p class="delete" @click="delePop([scope.row.id])">删除</p>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="custom_container">
        <el-pagination @size-change="pageNum" @current-change="pageChange" :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]" :page-size="pageSize" layout="sizes, prev, pager, next, jumper"
          :total="pageData.length" class="custom_pagination" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { lsrkTypeList, lsrkTypeAdd, lsrkTypeDel } from '/@/api/lark/lark_type/index';
import { larkTypeGroupList } from '/@/api/lark/lark_type_group/index';
import { ElMessage, FormInstance, FormRules, UploadFile } from 'element-plus';
import { ElMessageBox } from 'element-plus';
import { fileUpload } from '/@/api/login';
import { url } from '/@/api/url';


interface FoodType {
  id: number;
  title: string;
  createtime: string;
}

const data = ref<FoodType[]>([]);
const pageData = ref<FoodType[]>([]);
// 分页页数
const currentPage = ref(1);
// 一页的数据
const pageSize = ref(10);
const group = ref<FoodType[]>([]);
const editId = ref(0);
const search = reactive({
  title: '',
  time: '',
})
const formRef = ref<FormInstance>();

const editForm = reactive({
  id: '',
  title: '',
  img: '',
  group_id: '',
})

const repeat = (rule: any, value: any, callback: any) => {
  // 检查是否有重复标题（排除当前编辑的条目）
  const isDuplicate = data.value.some(item =>
    item.title === value &&
    item.id !== editId.value // 如果是编辑模式，跳过当前条目
  );
  if (isDuplicate) {
    callback(new Error('不能添加重复的店铺'));
  } else {
    callback(); // 验证通过
  }
}

const editFormRoules = reactive<FormRules>({
  title: [
    { required: true, message: '请输入店铺名称', trigger: 'blur' },
    { validator: repeat, trigger: 'blur' }
  ],
  group_id: [
    { required: true, message: '请选择门店类型分组', trigger: ['change', 'blur'] }
  ],
  img: [
    { required: true, message: '请上传图片', trigger: ['change', 'blur'] }
  ],
})
// 弹窗状态
const alertState = ref(false);
// 弹窗title
const alertTitle = ref('');

const getData = () => {
  lsrkTypeList().then((res: any) => {
    console.log(res)
    data.value = res.data;
    pageData.value = res.data;
    getgroup();
  })
}
getData();

const getgroup = () => {
  larkTypeGroupList().then((res: any) => {
    console.log(res)
    group.value = res.data;
  })
}

// 计算当前页码的起始索引和结束索引，并返回对应区间的数据
const pageCount = computed(() => {
  // 计算起始索引，基于当前页码和每页大小
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return pageData.value.slice(start, end);
});
/* 分页改变 */
const pageChange = (val: number) => {
  currentPage.value = val;
};
/* 分页大小改变 */
const pageNum = (val: number) => {
  pageSize.value = val;
  currentPage.value = 1;
};

// 获取全选的id
const selectedIds = ref<any[]>([]);
const checkall = (val: any) => {
  selectedIds.value = val.map((item: any) => item.id).filter((id: number) => id);
};

// 添加弹窗
const addAlter = () => {
  alertTitle.value = '添加';
  alertState.value = true;
  editForm.id = '';
}

// 编辑弹窗
const editAlter = (item: any) => {
  alertTitle.value = '编辑';
  editId.value = item.id;
  alertState.value = true;
  editForm.title = item.title;
  editForm.id = item.id;
  editForm.group_id = item.group_id,
    editForm.img = item.img;
  const img = item.img.startsWith(url) ? item.img : url + item.img;
  fileimg.value = img
    ? [
      {
        uid: Date.now(),
        name: 'avatar',
        url: img,
        status: 'success',
      },
    ]
    : [];
}
// 添加确认接口
const affirm = async (formEl: FormInstance | undefined) => {
  await formEl?.validate((valid, fields) => {
    if (valid) {
      lsrkTypeAdd({
        id: editForm.id,
        title: editForm.title,
        group_id: editForm.group_id,
        img: editForm.img,
      }).then((res) => {
        console.log(res);
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        formRef.value?.resetFields();
        alertState.value = false;
        getData();
      });
    }
  });
}
// 关闭弹窗函数
const cancel = () => {
  alertState.value = false;
  editForm.title = '';
  editForm.id = '';
  formRef.value?.resetFields();
};

const delePop = (id: any) => {
  if (id.length <= 0) {
    ElMessage.error('请选择要删除的数据')
    return;
  }
  ElMessageBox.confirm("确定要删除这些数据吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    lsrkTypeDel({ ids: id.join() }).then((res) => {
      if (res.code == 1) {
        ElMessage.success(res.msg);
        getData();
      }
    }).catch((error: any) => {
      console.log(error);
    })
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

// 搜索函数
const searchData = () => {
  pageData.value = data.value;
  const filteredData = () => {
    // 无搜索词时返回全部数据
    if (search.title == '' && search.time.length == 0) {
      return (pageData.value = data.value);
    }
    return pageData.value.filter((item) => {
      console.log(item.createtime);

      // 检查每个字段是否满足相应条件（如果该搜索条件存在）
      const nameMatch =
        !search.title || (item.title && item.title.toLowerCase().includes(search.title.toLowerCase()));
      const timeMatch =
        search.time.length == 0 ||
        (item.createtime >= search.time[0] && item.createtime <= search.time[1]);
      return nameMatch && timeMatch;
    });
  };
  pageData.value = filteredData();
};

const imgsState = ref(false);
// 图片上传
const fileimg = ref<UploadFile[]>([])  // 关键：维护文件列表
// 图片预览的路径
const dialogImageUrl = ref(<any>[]);
// 图片上传
const handleFileChange = async (file: UploadFile) => {
  // 创建本地预览
  file.url = URL.createObjectURL(file.raw!);
  fileimg.value = [file];
  // 上传到服务器
  const formData = new FormData();
  formData.append('file', file.raw!);
  console.log(formData);
  fileUpload(formData).then(res => {
    editForm.img = res.data.url;
    formRef.value?.clearValidate('img');
  }).catch((error) => {
    fileimg.value = [];
    editForm.img = '';
    ElMessage.error('上传失败');
    handleRemove();
    formRef.value?.validateField('img');
  });
}
// 图片删除
const handleRemove = (file?: UploadFile) => {
  fileimg.value = [];
  editForm.img = '';
  formRef.value?.validateField('img');
};

// 图片预览
const handleimgsPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url; // 优先显示服务器URL
  imgsState.value = true;
};


</script>

<style scoped>
.content {
  padding: 50px;
  margin: 2%;
  position: relative;
  background-color: white;
}

.line {
  width: 100%;
  height: 1px;
  margin: 25px 0;
  background-color: #e8e7e7;
}

.search_form {
  width: 100%;
  display: flex;
  margin-bottom: -22px;
}

.search_input {
  width: 240px;
  margin-right: 30px;
}

.input_height {
  height: 33px;
}

.button_height {
  height: 30px;
}

.operateBtn {
  display: flex;
  margin-top: 10px;
}

.label {
  margin-top: 10px;
}

.operate_box {
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit {
  color: #409EFF;
  cursor: pointer;
  margin: 0px 10px;
}

.delete {
  color: #F56C6C;
  cursor: pointer;
  margin: 0px 10px;
}

.custom_container {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 10px;
}

.editAlert {
  position: absolute;
  width: 100%;
  overflow: auto;
  background-color: white;
  top: 0;
  right: 0;
  z-index: 30;
}

.Pop_title {
  padding: 2%;
  border-bottom: 1px solid #ddd;
}

.editForm {
  padding: 2%;
}

.footer_btn {
  display: flex;
  justify-content: end;
  margin-top: 10%;
  margin-right: 5%;
  margin-bottom: 2%;
}

.rigthBtn {
  margin-left: 5%;
}




.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader {
  position: relative;
  display: inline-block;
}

.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

/* 隐藏上传按钮当有图片时 */
.hide-upload :deep(.el-upload) {
  display: none;
}

/* 在全局或组件样式添加 */
.avatar-uploader :deep(.el-upload-list__item) {
  transition: none !important;
}

.map_container {
  width: 240px;
  height: 180px;
}

.preview-img {
  width: 100%;
}
</style>